package com.example.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;

/**
 * 认证服务器配置
 */
@Configuration
@EnableAuthorizationServer//开启认证服务
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter{
    /**
     * 密码模式+客户端模式
     */
    @Autowired private PasswordEncoder passwordEncoder;
    @Autowired private AuthenticationManager authenticationManager;
    @Autowired private TokenStore tokenStore;
    @Autowired private UserDetailsService userDetailsService;
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client").secret(passwordEncoder.encode("secret"))
                .scopes("all","read","write")
                .authorizedGrantTypes("client_credentials","refresh_token","implicit")

                .and()
                .withClient("client2")
                .secret(passwordEncoder.encode("secret"))
                .authorizedGrantTypes("password","authorization_code","refresh_token")
                .scopes("all","read","write")
                .redirectUris("http://www.baidu.com")
                .authorities("user","login","authorize")
//                .autoApprove("oauth")//添加需要授权的scope，若不设置默认所有scope
                .autoApprove(true);//若不加该设置，会出现授权页面
    }
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients();//密码模式需要
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)//密码模式必须添加验证方式
                .tokenStore(tokenStore)
                .userDetailsService(userDetailsService)
        ;
    }
}
